package priv.mill.controller;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import priv.mill.controller.util.RetenObj;
import priv.mill.entry.Order;
import priv.mill.server.OrderService;

@Controller
@RequestMapping("Order")
public class OrderController {

	@Autowired
	private OrderService orderService;

	private static final Logger logger = Logger.getLogger(OrderController.class);

	@RequestMapping("getOrderById")
	@ResponseBody
	public RetenObj getOrderById(@RequestParam("OrderId") Integer orderId) {
		try {
			return warpData(orderService.getOrderById(orderId), 200);
		} catch (Exception e) {
			logger.error(e.getMessage());
			return warpData(null, 500);
		}
	}

	private RetenObj warpData(Object object, int i) {
		RetenObj retenObj = new RetenObj();
		retenObj.setData(object);
		retenObj.setStatus(i);
		return retenObj;
	}

	@RequestMapping("getOrderByEntry")
	@ResponseBody
	public RetenObj getOrderByEntry(Order order) {
		try {
			return warpData(orderService.getOrderByEntry(order), 200);
		} catch (Exception e) {
			logger.error(e.getMessage());
			return warpData(null, 500);
		}
	}

	@RequestMapping("getOrdersByPage")
	@ResponseBody
	public RetenObj getOrdersByPage(Order order) {
		try {
			return warpData(orderService.getOrdersByPage(order), 200);
		} catch (Exception e) {
			logger.error(e.getMessage());
			return warpData(null, 500);
		}
	}

	@RequestMapping("updateOrder")
	@ResponseBody
	public RetenObj updateOrder(Order order) {
		try {
			int result = orderService.updateOrder(order);
			if (result > 0)
				return warpData(result, 200);
			else
				return warpData(result, 300);
		} catch (Exception e) {
			logger.error(e.getMessage());
			return warpData(null, 500);
		}
	}
	

	@RequestMapping("insertOrder")
	@ResponseBody
	public RetenObj insertOrder(Order order) {
		try {
			int result = orderService.insertOrder(order);
			if (result > 0)
				return warpData(order.getOid(), 200);
			else
				return warpData(result, 300);
		} catch (Exception e) {
			logger.error(e.getMessage());
			return warpData(null, 500);
		}
	}

	@RequestMapping("deleteOrder")
	
	@ResponseBody
	public RetenObj deleteOrder(Integer orderId) {
		try {
			int result = orderService.deleteOrder(orderId);
			if (result > 0)
				return warpData(result, 200);
			else
				return warpData(result, 300);
		} catch (Exception e) {
			logger.error(e.getMessage());
			return warpData(null, 500);
		}

	}
}
